package vip.xiaonuo.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.Reactor;
import reactor.event.Event;
import reactor.function.Consumer;
import vip.xiaonuo.facedoor.modular.device.entity.DeviceCategory;
import vip.xiaonuo.facedoor.modular.memberfeatures.entity.MemberFeatures;
import vip.xiaonuo.facedoor.modular.memberfeatures.param.MemberFeaturesParam;
import vip.xiaonuo.facedoor.modular.memberfeatures.service.MemberFeaturesService;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.topic.AiBoxEventTopic;
import vip.xiaonuo.megvii.faces.model.FaceDelete;
import vip.xiaonuo.megvii.service.DeviceMegviiFaceGroupFaceTokenRelaService;
import vip.xiaonuo.megvii.service.DeviceMegviiFaceService;
import vip.xiaonuo.megvii.service.query.DeviceMegviiQueryService;
import vip.xiaonuo.modular.devicemegvii.entity.DeviceMegvii;
import vip.xiaonuo.modular.facegroupfacetokenrela.param.FaceGroupFaceTokenRelaSave;
import vip.xiaonuo.modular.facegroupfacetokenrela.service.FacegroupFacetokenRelaService;
import vip.xiaonuo.modular.megviifacegroup.entity.MegviiFaceGroup;
import vip.xiaonuo.modular.megviifacegroup.mapper.MegviiFaceGroupMapper;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

import static reactor.event.selector.Selectors.$;

@Service
@Slf4j
public class MemberUserAvatarChangeListener implements Consumer<Event<MemberUser>>, InitializingBean {

    @Autowired
    private Reactor reactor;

    @Resource
    private DeviceMegviiFaceService faceService;

    @Resource
    private MemberFeaturesService featuresService;

    @Resource
    private DeviceMegviiQueryService queryService;

    @Resource
    private MegviiFaceGroupMapper faceGroupMapper;

    @Resource
    private DeviceMegviiFaceGroupFaceTokenRelaService groupTokenRelaService;

    @Override
    public void afterPropertiesSet() throws Exception {
        reactor.on($(AiBoxEventTopic.AVATAR_CHANGE), this);
    }

    @Override
    public void accept(Event<MemberUser> event) {
        MemberUser user = event.getData();
        doAvatarChange(user);
    }

    /**
     * 1. 已有人脸删除
     * 2. 新加人脸入库
     * 3. 重新绑定分组
     * @param user
     */
    private void doAvatarChange(MemberUser user){
        // 1.先查出当前已有的数据
        MemberFeaturesParam param = new MemberFeaturesParam();
        param.setDwMemberUserId(user.getId());
        param.setPlatform(DeviceCategory.SUB_TYPE_BOX);
        List<MemberFeatures> currentFeatures = featuresService.listByUserId(param);
        for(MemberFeatures feature : currentFeatures){
            if(ObjectUtil.isEmpty( feature.getImageId()) ){// 没有对应的imgid,无法与旷视后台进行交互，该数据直接删除
                featuresService.removeById(feature);
            }else{
                FaceDelete faceDelete = BeanUtil.copyProperties(feature, FaceDelete.class);
                faceDelete.setDeleteMode(1);
                faceService.faceDelete(faceDelete);
            }
        }
        // 2.再次入库
        faceService.faceInStore(user);

        // 3.新的特征值,重新绑定分组关联
        this.doChangeRelate(user);
    }

    private void doChangeRelate(MemberUser user){
        List<DeviceMegvii> devices = queryService.getDeviceByUser(user);

        for(DeviceMegvii device : devices){
            // 根据设备和人获取关联的人脸分组
            List<MegviiFaceGroup> faceGroups = faceGroupMapper.listFaceGroupByUserAndDevice(user.getId(),device.getId());

            List<Long> addRelates = new ArrayList<>();
            faceGroups.forEach(obj ->{
                addRelates.add(obj.getId());
            });

            // 获取当前人员在当前设备下的人脸数据
            MemberFeaturesParam param = new MemberFeaturesParam();
            param.setDwMemberUserId(user.getId());
            param.setBizDeviceId(device.getId());
            List<MemberFeatures> features = featuresService.list(param);

            for(MemberFeatures feature : features){
                FaceGroupFaceTokenRelaSave saveBean = new FaceGroupFaceTokenRelaSave();
                saveBean.setFeaturesId(feature.getId());
                saveBean.setAddRelate(addRelates);
                groupTokenRelaService.saveFaceGroupRelation(saveBean);
            }
        }
    }

}
